<template>
  <!--答题页面-->
  <view v-if="detail">
    <view class="answer-index flex flex-column around">
      <!--头部导航-->
      <navbar ref="navbar" :font-size="fontSize" :title="detail.practiceName" :isAnswerShow="detail.answerToShow"
        @editFontSize="fontSize = $event" @updateAutomatic="automatic = $event" @updateIsAnswer="isAnswer = $event"></navbar>

      <view class="submit-box flex between">
        <view class="f_1 flex time">
          <text>考试倒计时</text>
          <u-count-down :time="secondTime * 1000" @finish="submitPaper" v-if="detail.time"></u-count-down>
          <text v-else>--</text>
        </view>
        <view class="btn" @click="submitPaper">交卷</view>
      </view>

      <view class="content f_1 flex flex-column " @click="clNavbarPup">
        <view class="swiper-item f_1 f_1 flex-column" @touchstart="touchStart" @touchend="touchEnd">
          <!--判断题-->
          <BooleanQuestion v-if="currentItem.type === '0101'" :font-size="fontSize" :item="currentItem"
            :answerNumber="currentIndex + 1" :showAnswer="isAnswer" @updateAnswers="updateAnswers"></BooleanQuestion>
          <!--单选题-->
          <RadioQuestion v-if="currentItem.type === '0201'" :font-size="fontSize" :item="currentItem"
            :answerNumber="currentIndex + 1" :showAnswer="isAnswer" @updateAnswers="updateAnswers"></RadioQuestion>

          <!--多选题-->
          <MultipleQuestion v-if="currentItem.type === '0301'" :font-size="fontSize" :item="currentItem"
            :answerNumber="currentIndex + 1" :showAnswer="isAnswer" @updateAnswers="updateAnswers"></MultipleQuestion>

          <!--描述题-->
          <DescribeQuestion v-if="['si02', 'si02', 'si03', 'si04'].includes(currentItem.type)" :font-size="fontSize"
            :item="currentItem" :answerNumber="currentIndex + 1" :showAnswer="isAnswer" @updateAnswers="updateAnswers">
          </DescribeQuestion>
        </view>
      </view>
      <!--底部导航-->
      <Menu :answerData="answerData" :current-number="currentIndex + 1" @next.stop="next" @prev.stop="prev"
        @openAnswerNav="openAnswerNav" class="fs_0"></Menu>
      <!--试题导航-->
      <AnswerNav :nav-list="navigationList" :answer-data="answerData" :currentIndex="currentIndex + 1" ref="AnswerNav"
        @navItemClick="navItemClick"></AnswerNav>

      <!--拍照区域-->
      <view v-show="isPhoto" style="position: absolute;bottom:60rpx;right:0" @click="isPhoto = false">
        <ExamPhoto ref="childRef"></ExamPhoto>
      </view>
      <!--切屏警告-->
      <CutScreenMsg :last-num="lastNum" :is-popup="isCutScreen" @close="isCutScreen = false"></CutScreenMsg>

      <!--交卷确认弹窗-->
      <SubmitAnswerConfirm ref="SubmitAnswerConfirm" @confirm="confirmSubmitPaper"></SubmitAnswerConfirm>

      <!--签名弹窗-->
      <SignPopup v-if="isSign" @success="signSuccess" @close="isSign = false"></SignPopup>

      <!--答完清空弹窗提示-->
      <Popup ref="clearPopup" :show-close-btn="false" :show-confirm-btn="false">
        <view class="clearMsg flex flex-column item-center">
          <image src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/practice.svg" />
          <text>当前练习已全部完成，可在试题导航中清空练习记录重新练习</text>
        </view>
      </Popup>

    </view>
  </view>

</template>
<script>

import { countLastCutTime, getPracticeSet, recordCutTimes } from "@/improve/services";
import Navbar from "../components/answer/Navbar.vue";
import BooleanQuestion from "../components/answer/question/BooleanQuestion.vue";
import Menu from "../components/answer/Menu.vue";
import RadioQuestion from "../components/answer/question/RadioQuestion.vue";
import MultipleQuestion from "../components/answer/question/MultipleQuestion.vue";
import DescribeQuestion from "../components/answer/question/DescribeQuestion.vue";
import AnswerNav from "../components/answer/AnswerNav.vue";
import ExamPhoto from "../components/faciaPhoto/ExamPhoto.vue";
import CutScreenMsg from "../components/answer/CutScreenMsg.vue";
import SubmitAnswerConfirm from "../components/answer/SubmitAnswerConfirm.vue";
import SignPopup from "../components/answer/SignPopup.vue";
import Popup from "@/improve/components/common/Popup.vue";
import { titleMap } from '@/improve/components/enum'

export default {
  name: "practiceView",
  components: {
    Popup,
    SignPopup,
    SubmitAnswerConfirm,
    CutScreenMsg,
    ExamPhoto, AnswerNav, DescribeQuestion, MultipleQuestion, RadioQuestion, Menu, BooleanQuestion, Navbar
  },
  data() {
    return {
      loading: true,
      upgPracticeUuid: "",
      detail: null,
      fontSize: 32, // 题目字体大小
      automatic: false, //自动换题
      isAnswer: true,//是否显示答案
      startX: 0, // 触摸开始的X坐标
      endX: 0, // 触摸结束的X坐标
      currentIndex: 0, //当前显示题目的下标
      currentItem: null,
      secondTime: 1000,//倒计时
      lastNum: null,//剩余切屏次数
      isCutScreen: false, //是否切屏
      activeSatus: false, // 切屏控制 true时 强制交卷
      windowHeight: '',
      isPhoto: false,  //是否显示拍照区域
      intervalId: null,//定时
      isSign: false,
      answerData: {
        total: 0, //总数
        isCollect: false, //是否收藏
        collectTotal: 0,//收藏个数
        successTotal: 0, //答对数量
        errorTotal: 0, //打错数量
      },
      list: [
        {
          analysis: null,
          answer: "",
          collectStatus: 0,
          correct: null,
          hasAnswer: false,
          hierarchy: "5691,5790,5845,5846,5861,",
          itemId: 17530,
          itemNo: 218,
          itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
          itemText: "请回答描述题",
          itemTypeName: "多选题",
          itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
          scoreRule: null,
          selections: ``,
          structId: 5861,
          stuAnswer: null,
          subjectId: 24,
          type: "si02",

        },
        {
          analysis: null,
          answer: "A,B,C",
          collectStatus: 0,
          correct: null,
          hasAnswer: false,
          hierarchy: "5691,5790,5845,5846,5861,",
          itemId: 17530,
          itemNo: 218,
          itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
          itemText: "螺旋输送机持续运转使用，每（ ）检查油位油质，油位不足及时补充。第一次使用（ ）后应更换一次润滑油。",
          itemTypeName: "多选题",
          itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
          scoreRule: null,
          selections: `[{"code":"A","context":"5天，300小时"},{"code":"B","context":"7天，300小时"},{"code":"C","context":"5天，500小时"},{"code":"D","context":"7天，500小时"}]`,
          structId: 5861,
          stuAnswer: null,
          subjectId: 24,
          type: "0301",

        },
        {
          analysis: null,
          answer: "A",
          collectStatus: 0,
          correct: true,
          hasAnswer: false,
          hierarchy: "5691,5790,5815,5816,5822,",
          itemId: 17320,
          itemNo: 8,
          itemStruct: "全部>相关知识>使用工具与操作井场环保设备>使用工具>千斤顶的分类",
          itemText: "液压千斤顶的液压油除了用于液压传动系统中作中间介质，起传递和转换能量作用，还在用时起着液压系统内各部件间的润滑、防腐、冷却、冲洗等作用。",
          itemTypeName: "判断题",
          itemUuid: "182805fe50424dcbb42d6f131644fb9a",
          scoreRule: null,
          selections: null,
          structId: 5822,
          stuAnswer: null,
          subjectId: 24,
          type: "0101",
        },
        {

          analysis: null,
          answer: "A",
          collectStatus: 0,
          correct: null,
          hasAnswer: false,
          hierarchy: "5691,5790,5845,5846,5861,",
          itemId: 17530,
          itemNo: 218,
          itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
          itemText: "螺旋输送机持续运转使用，每（ ）检查油位油质，油位不足及时补充。第一次使用（ ）后应更换一次润滑油。",
          itemTypeName: "单选题",
          itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
          scoreRule: null,
          selections: `[{"code":"A","context":"5天，300小时"},{"code":"B","context":"7天，300小时"},{"code":"C","context":"5天，500小时"},{"code":"D","context":"7天，500小时"}]`,
          structId: 5861,
          stuAnswer: null,
          subjectId: 24,
          type: "0201",
        },
        {
          itemUuid: "eabff72d82074d0daaf1bee0d59b91fb", hasAnswer: true, correct: true,
          item: {
            analysis: null,
            answer: "A,B,C",
            collectStatus: 0,
            correct: null,
            hasAnswer: false,
            hierarchy: "5691,5790,5845,5846,5861,",
            itemId: 17530,
            itemNo: 218,
            itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
            itemText: "螺旋输送机持续运转使用，每（ ）检查油位油质，油位不足及时补充。第一次使用（ ）后应更换一次润滑油。",
            itemTypeName: "多选题",
            itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
            scoreRule: null,
            selections: `[{"code":"A","context":"5天，300小时"},{"code":"B","context":"7天，300小时"},{"code":"C","context":"5天，500小时"},{"code":"D","context":"7天，500小时"}]`,
            structId: 5861,
            stuAnswer: null,
            subjectId: 24,
            type: "0301",
          }
        },
      ],
      //题目导航
      navigationList: [
        { itemUuid: "9ccba2f5d05a432d8bdc31e61166e127", hasAnswer: true, correct: true, collectStatus: true },
        { itemUuid: "a189d8976c5e465d811ccbfa380a96b4", hasAnswer: true, correct: false, collectStatus: false },
        { itemUuid: "eabff72d82074d0daaf1bee0d59b91fb", hasAnswer: true, correct: true, collectStatus: false },
        { itemUuid: "478b9e2bbe3a4e01a458d115c8b410dd", hasAnswer: true, correct: false, collectStatus: false },
        { itemUuid: "127376e6f4e346b4be087444be3151ef", hasAnswer: true, correct: false, collectStatus: false },
      ]
    }
  },
  watch: {
    navigationList: {
      deep: true, // 深度监听
      handler(newItems, oldItems) {
        this.answerData.successTotal = this.navigationList.filter((item) => item?.correct)?.length
        this.answerData.errorTotal = this.navigationList.filter((item) => !item?.correct)?.length
        this.answerData.collectTotal = this.navigationList.filter((item) => !item?.isCollect)?.length
        this.answerData.total = this.navigationList.length
      },
    },
  },
  methods: {
    getDetails() {
      uni.showLoading({
        title: '加载中'
      });
      getPracticeSet(this.upgPracticeUuid).then(res => {
        this.detail = res;
        wx.setNavigationBarTitle({
          title: titleMap[this.detail.practiceType]
        });
        if (this.detail.noLeaving) {
          wx.onAppShow(this.onStopEvent)
          wx.onAppHide(this.onBackEventTime)
        }
        uni.hideLoading();
      })
    },
    getList() {
      //查询第一道题目具体内容
      this.getTopicInfo()
      this.navigationList.push({})
    },
    getTopicInfo() {
      //根据当前切换的下标值获取uuid 去查询
      this.currentItem = this.list[this.currentIndex]
      this.answerData.isCollect = this.currentItem.collectStatus  //当前题目是否搜藏
      //选项转json
      if (this.currentItem.selections) {
        try {
          this.currentItem.selections = JSON.parse(this.currentItem.selections)
        } catch (e) {

        }
      }
    },
    touchStart(event) {
      this.startX = event.touches[0].clientX;
    },
    touchEnd(event) {
      this.endX = event.changedTouches[0].clientX;
      if (this.endX - this.startX > 50) { // 右滑
        this.prev()
      } else if (this.startX - this.endX > 50) { // 左滑
        this.next()
      }
    },
    async next() {
      //未提交答案时
      if (!this.currentItem.hasAnswer) {
        await this.submitAnswers()
      }
      if (this.currentIndex >= this.list.length - 1) {
        return;
      }
      this.currentIndex++;
      this.getTopicInfo()
    },
    async prev() {
      //未提交答案时
      if (!this.currentItem.hasAnswer) {
        await this.submitAnswers()
      }
      if (this.currentIndex === 0) {
        return
      }
      this.currentIndex--;
      this.getTopicInfo()
    },
    //关闭设置弹窗
    clNavbarPup() {
      this.$refs.navbar.hide()
    },
    //打开导航弹窗
    openAnswerNav() {
      this.$refs.AnswerNav.open();
    },
    //导航点击事件
    navItemClick(index) {
      console.log("navItemClick", index)
      //当前题有答案且没有提交 提交一下
      if (this.currentItem.stuAnswer && !this.currentItem.hasAnswer) {
        this.submitAnswers(false)
      }
      //切换到指定题
      this.currentIndex = index;
      this.getTopicInfo()
      this.$refs.AnswerNav.close();
    },
    /**
     *
     * @param index 当前题目类型
     * @param stuAnswer 用户选择答案
     * @param submit 是否提交
     */
    updateAnswers({ index, stuAnswer, submit }) {
      console.log("更新答案为", stuAnswer)
      //提交答案（后端接入后修改为接口查询）
      this.currentItem.stuAnswer = stuAnswer
      //开启显示答案 自动提交，否则点击下一道或者上一道提交答案
      if (submit) {
        this.submitAnswers()
      }
    },
    //提交答案
    async submitAnswers(isNext = true) {
      //提交答案（后端接入后修改为接口）
      if (!this.currentItem.stuAnswer) {
        return
      }
      console.log("提交答案")
      this.currentItem.correct = true
      this.currentItem.hasAnswer = true
      if (this.automatic && isNext) {
        setTimeout(() => {
          this.next()  //自动换题进入下一道
        }, 600)
      }
    },
    //交卷
    submitPaper() {
      this.$refs.SubmitAnswerConfirm.open()
      console.log("交卷")
    },
    confirmSubmitPaper() {
      //进行签名
      if (this.detail.signConfirmFlag) {
        this.isSign = true
        return;
      }
      uni.navigateTo({
        url: "/improve/answer/result"
      })
      console.log("确认交卷")
    },
    //签名完成
    signSuccess() {
      //关闭所有页面，打开到应用内的某个页面。(uni.reLaunch)
      uni.reLaunch({
        url: "/improve/answer/result"
      })
    },
    onUToastShow(showType) {
      const type = showType === 'active' ? '次数' : '时长'
      let timeInt = setInterval(() => {
        if (this.time === 0) {
          clearInterval(timeInt)
          this.submitPaper()
        } else {
          this.time--
        }
      }, 1000)
    },
    //记录切屏
    onBackEventTime() {
      recordCutTimes().then(res => {
        this.lastNum = res.lastNum
        if (res.locked) {
          this.activeSatus = true
        }
      })
    },
    //切屏后重新激活
    onStopEvent() {
      countLastCutTime().then(res => {
        if (this.activeSatus) {
          this.onUToastShow('active')
        } else {
          if (res) {
            this.onUToastShow('time')
          } else {
            this.isCutScreen = true
          }
        }
      })
    },
    openPhone() {
      if (!this.detail.intervals) {
        return
      }
      this.intervalId = setInterval(() => {
        this.isPhoto = true
        console.log("打开相机")
        setTimeout(() => {
          this.$refs.childRef.takePhoto().then(res => {
            const base64Data = res.split(",")[1]; // 截取除头部信息以外的数据部分
            console.log("拍照", base64Data);
            this.isPhoto = false
          }).catch(err => {
          })
        }, 3000)
      }, (this.detail.intervals * 60 * 1000) + 3000);   //每隔几分钟打开照相机 3秒截取内容
    },
    windowResizeCallback(res) {
      console.log('变化后的窗口宽度=' + res.size.windowWidth)
      console.log('变化后的窗口高度=' + res.size.windowHeight)
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    //this.openPhone() 调试阶段关闭
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    //uni.offWindowResize(windowResizeCallback)
  },
  onUnload() {
    wx.offAppShow()
    wx.offAppHide()
  },
  onLoad(options) {
    uni.getSystemInfo({
      success: (res) => {
        this.windowWidth = res.windowWidth
        this.windowHeight = res.windowHeight
      }
    })
    this.upgPracticeUuid = options.upgPracticeUuid
    this.getDetails()
  },
  onShow() {
    const windowResizeCallback = (res) => {
      if (res.size.windowHeight !== this.windowHeight) {
        console.log('进来了')
        if (this.detail.noLeaving) {
          console.log("开启了切屏监听")
          this.onStopEvent()
          this.onBackEventTime()
        }
      }
      console.log('变化后的窗口宽度=' + res.size.windowWidth, this.windowWidth)
      console.log('变化后的窗口高度=' + res.size.windowHeight, this.windowHeight)
    }
    uni.onWindowResize(windowResizeCallback)
  },
}
</script>

<style scoped lang="scss">
.answer-index {
  width: 100vw;
  background-color: #FFFFFF;
  padding-bottom: calc(10px + env(safe-area-inset-bottom));
  height: calc(100vh - 10px - env(safe-area-inset-bottom));

  .head {
    background-color: #FFFFFF;
    border-bottom-left-radius: 24rpx;
    border-bottom-right-radius: 24rpx;
    padding: 10px 20px;

    image {
      width: 100%;
      height: 116px;
      background-size: cover;
      border-radius: 4px;
    }

    .info {
      margin-top: 12px;

      .name {
        margin-right: 10px;
        color: #333333;
        font-size: 16px;
      }

      >view {
        font-size: 12px;
        color: #666666;

        image {
          width: 20px;
          height: 20px;
          margin-right: 6px;
        }
      }
    }
  }

  .line {
    width: 100%;
    background-color: #F5F5F5;
  }

  .submit-box {
    padding: 18px;

    .time text {
      font-size: 16px;
      color: #333333;
    }

    ::v-deep .u-count-down {

      text {
        font-size: 16px !important;
        color: #37B874 !important;
        margin-left: 5px;
        font-weight: bold;
      }
    }

    .btn {
      background-color: #37B874;
      width: 55px;
      height: 24px;
      text-align: center;
      line-height: 24px;
      border-radius: 7px;
      font-size: 14px;
      color: #FFFFFF;
    }

  }

  .btn-item {
    padding-top: 20px;
    padding-bottom: calc(10px + env(safe-area-inset-bottom));
    position: fixed;
    background-color: #FFFFFF;
    box-shadow: 1px 1px 4px 2px rgba(0, 0, 0, 0.12);
    bottom: 0;
    width: 100%;
    z-index: 99;

    .btn {
      background-color: #37B874;
      border-radius: 24rpx;
      width: calc(100% - 40px);
      height: 90rpx;
      text-align: center;
      line-height: 90rpx;
      font-size: 32rpx;
      color: #FFFFFF;
      margin-left: 20px;
    }
  }

  .content {
    padding-bottom: calc(90px + env(safe-area-inset-bottom));
    margin-top: 10px;
    background-color: #FFFFFF;
    border-top-left-radius: 24rpx;
    border-top-right-radius: 24rpx;

    .user-info {
      padding: 16px 20px;

      image {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        margin-right: 16px;
      }

      .user-account {
        color: #333333;
        font-size: 14px;

        .nickname {
          font-size: 16px;

          label {
            padding: 1px 5px;
            background-color: #EED682;
            color: #A86C12;
            font-size: 10px;
            margin-left: 9px;
            border-radius: 4px;
            height: fit-content;
          }
        }
      }
    }

    .practice-info {
      .item {
        height: 60px;
        padding: 0 20px;
        border-bottom: solid 1px #F2F2F2;

        .label {
          font-size: 32rpx;
          color: #333333;
        }

        text {
          margin-left: 16px;
          font-size: 16px;
          color: #999999;
          text-align: right;
        }
      }
    }


  }

  .clearMsg {
    padding-bottom: 40px;

    image {
      width: 50%;
    }

    text {
      font-size: 14px;
      width: 60%;
      line-height: 24px;
      text-align: center;
    }
  }
}
</style>